package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * app端登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        //校验参数
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //判断是否为游客
        if (dto.getPhone().equals("") && dto.getPassword().equals("")) {
            //登录用户为游客 生成token
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0l));

            //响应数据
            return ResponseResult.okResult(map);
        } else {
            //非游客登录 校验密码
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (null == apUser) {
                //数据未查出 手机号错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_NAME_ERROR);
            }

            //获取加密后的密码
            String pasw = dto.getPassword() + apUser.getSalt();
            String encode = MD5Utils.encode(pasw);

            //密码比对
            if (!apUser.getPassword().equals(encode)) {
                //密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //密码正确 生成token
            Map<String, Object> map = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("user", apUser);

            //响应数据
            return ResponseResult.okResult(map);
        }
    }
}
